package com.magicborrow.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.volley.VolleyError;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.alipay.PayResult;
import com.magicborrow.beans.ApplyEntity;
import com.magicborrow.beans.BaseBean;
import com.magicborrow.enums.PriceModeEnum;
import com.magicborrow.huanxin.Constant;
import com.magicborrow.utils.StringUtil;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.views.MsgDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.HashMap;

public class PayActivity extends BaseActivity implements View.OnClickListener {

    private ImageView imbBack;
    private ImageView imvStuff;
    private TextView tvName;
    private TextView tvUserName;
    private TextView tvPrice;
    private TextView tvRent;
    private TextView tvTime;
    private TextView tvTotalAmount;
    private int payId;
    private ApplyEntity.ContentData data;
    private String signInfo;
    private static final int SDK_PAY_FLAG = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        //  payId = getIntent().getIntExtra("payId", 0);
        data = (ApplyEntity.ContentData) getIntent().getSerializableExtra("data");
        payId = data.getId();
        initVIew();

        initPayInfo();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //  Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        MsgDialog dialog = new MsgDialog(PayActivity.this, "支付成功", null);
                        dialog.show();
                        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                finish();
                            }
                        });

                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            //  Toast.makeText(PayActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                            MsgDialog dialog = new MsgDialog(PayActivity.this, "支付结果确认中，请稍候", null);
                            dialog.show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            //    Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                            MsgDialog dialog = new MsgDialog(PayActivity.this, "支付失败，请稍候再试", null);
                            dialog.show();


                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    private void initVIew() {
        imbBack = (ImageView) findViewById(R.id.imb_back);
        imvStuff = (ImageView) findViewById(R.id.imv_stuff);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvUserName = (TextView) findViewById(R.id.tv_user_name);
        tvPrice = (TextView) findViewById(R.id.tv_price);
        tvRent = (TextView) findViewById(R.id.tv_rent);
        tvTime = (TextView) findViewById(R.id.tv_time);
        tvTotalAmount = (TextView) findViewById(R.id.tv_totalAmount);
        findViewById(R.id.btn_pay).setOnClickListener(this);
        ImageLoader.getInstance().displayImage(Constants.ADDRESS + data.getWare().getImages().get(0).getOrigin(), imvStuff);
        tvName.setText(data.getWare().getName());
        tvUserName.setText("物主：" + data.getUser().getNickname());
        tvPrice.setText("租金：￥" + data.getWarePrice() + "/" + PriceModeEnum.getModeStr(data.getWarePriceMode()));
        tvRent.setText("押金：￥" + data.getDepositPayment());
        //  tvBeginTime.setText(data.get);
        tvTime.setText("借用时间：" + data.getNumber() + PriceModeEnum.getModeStr(data.getWarePriceMode()));
        tvTotalAmount.setText("合计金额：￥" + (data.getDepositPayment() + data.getWarePrice() * data.getNumber()));
    }

    private void initPayInfo() {
        HashMap<String, String> params = new HashMap<>();
        params.put("acc_token", UserTools.getUser(this).getAcc_token());
        params.put("id", "" + payId);

        VolleyTool.get(Constants.URL_GET_PAYINFO, params, new VolleyTool.HTTPListener() {
            @Override
            public <T> void onResponse(T t, int requestCode) {
                BaseBean<String> bean = (BaseBean<String>) t;
                if (bean.getCode() >= 0) {
                    signInfo = bean.getData();
                    // signInfo = "_input_charset=utf_8&sign=fQIjdNZRbIk6ogXXPC8jsQYFd8I9NR9Bc89PP2mQl5swjhZdnsqPdfA0j5R7uDXBmy%2FqbaqnD5J74zcu%2BTYQcqd11pTlUhbZFyKxNQIKP8LMYT50GkPXIw8ezs9lz8lD9z%2B2jHDrXkGol%2FTaI9NclPzGwssj4a%2FGCpiLByH0Jw0%3D&sign_type=RSA";
                } else {
                    showShortMsg(bean.getMessage());
                }

            }

            @Override
            public void onErrorResponse(VolleyError error, int requestCode) {

            }
        }, 0, new BaseBean<String>().getClass());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_pay:
                //TODO implement

                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        // 构造PayTask 对象
                        PayTask alipay = new PayTask(PayActivity.this);
                        // 调用支付接口，获取支付结果
                        String result = alipay.pay(signInfo, true);

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();

                break;
        }
    }

    private double setDepositRul(int deposit) {
        double depositRul = 0;
        double s;

        if (deposit >= 1 && deposit < 1000) {
            depositRul = deposit * (1 - 7.0 / 10);

        } else if (deposit >= 1000 && deposit < 3000) {
            depositRul = deposit * (1 - 6.0 / 10);

        } else if (deposit >= 3000 && deposit < 10000) {
            depositRul = deposit * (1 - 7.0 / 10);

        } else if (deposit >= 10000 && deposit < 20000) {
            depositRul = deposit * (1 - 3.0 / 10);

        } else {
            depositRul = 0;
        }
        if (depositRul != 0) {
            s = depositRul;
        } else {
            s = 0;
        }
        return s;

    }
}

